package user

import (
	"gin-gorm-project/modules"
)

type User struct {
	Id           int    `gorm:"type:bigint(20);column:id;primary_key"`
	UserName     string `gorm:"type:varchar(64);column:user_name"`
	Password     string `gorm:"type:varchar(64);column:password"`
	Jurisdiction string `gorm:"type:varchar(64);column:jurisdiction"`
	Information  string `gorm:"type:varchar(64);column:information"`
}

// InitTable 使用gorm创建表
func InitTable() error {
	err := modules.DB.AutoMigrate(&User{})
	if err != nil {
		return err
	}
	return nil
}

func (user *User) TableName() string {
	return "user"
}

func (user *User) QueryAll() []User {
	var users []User
	modules.DB.Find(&users)
	return users
}

func (user *User) Save() {
	modules.DB.Save(user)
}

func (user *User) QueryByPage(pageNumber, pageSize int) []User {
	var response []User
	dbUtil := modules.DB
	if len(user.UserName) != 0 {
		dbUtil = dbUtil.Where("user_name like ?", "%"+user.UserName+"%")
	}
	if len(user.Password) != 0 {
		dbUtil = dbUtil.Where("password like ?", "%"+user.Password+"%")
	}
	if len(user.Jurisdiction) != 0 {
		dbUtil = dbUtil.Where("jurisdiction like ?", "%"+user.Jurisdiction+"%")
	}
	if len(user.Information) != 0 {
		dbUtil = dbUtil.Where("information like ?", "%"+user.Information+"%")
	}
	dbUtil.Limit(pageSize).Offset((pageNumber - 1) * pageSize).Find(&response)
	return response
}
